package com.sunspring.zdcall.controller.commoncontroller;

import com.sunspring.zdcall.common.SimpleResponse;
import com.sunspring.zdcall.common.exception.ZdException;
import com.sunspring.zdcall.quartz.SchedulerManager;
import com.sunspring.zdcall.quartz.entity.RegisterJobEntity;
import com.sunspring.zdcall.quartz.job.DbJob;
import com.sunspring.zdcall.quartz.job.RegisterJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

import static org.quartz.JobBuilder.newJob;

/**
 * quartz定时任务管理
 * @Author WuLei
 * @Date 2018/12/3  12:44
 */
@RestController
@RequestMapping("/sys/quartz")
@Slf4j
public class QuartzController {

    @Autowired
    private SchedulerManager schedulerManager;


    /**
     * 新增查询等系统的定时任务
     * @param rje RegisterJobEntity
     */
    @PostMapping("/add")
    public SimpleResponse addRegisterJob(@Valid RegisterJobEntity rje, BindingResult bindingResult) throws SchedulerException {
        if (bindingResult.hasErrors()) {
            throw new ZdException("创建定时任务，参数错误: " + bindingResult.getFieldError().getDefaultMessage());
        }
        schedulerManager.register(rje,RegisterJob.class);
        return SimpleResponse.success();
    }

    /**
     * 移除任务
     * @param jobName job名称
     * @param jobGroup job所在group名称
     */
    @PostMapping("/remove")
    public SimpleResponse removeJob(String jobName, String jobGroup) throws SchedulerException {
        schedulerManager.remove(jobName,jobGroup);
        return SimpleResponse.success();
    }

    /**
     * 暂停任务
     * @param jobName job名称
     * @param jobGroup job所在group名称
     */
    @PostMapping("/pause")
    public SimpleResponse pause(String jobName, String jobGroup) throws SchedulerException {
        schedulerManager.pause(jobName,jobGroup);
        return SimpleResponse.success();
    }

    /**
     * 恢复任务
     * @param jobName job名称
     * @param jobGroup job所在group名称
     */
    @PostMapping("/resume")
    public SimpleResponse resume(String jobName, String jobGroup) throws SchedulerException {
        schedulerManager.resume(jobName,jobGroup);
        return SimpleResponse.success();
    }



}
